package net.ruangtedy.java.spring.formhandling.web;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;






import net.ruangtedy.java.spring.formhandling.config.InfrastructureCtxConfig;
import net.ruangtedy.java.spring.formhandling.web.config.WebMvcCtxConfig;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

public class Initializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		registerDispatcherServlet(servletContext);
		registerListener(servletContext);
		
	}
	private void registerListener(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext rootContext;
        rootContext = createContext(InfrastructureCtxConfig.class);
        servletContext.addListener(new ContextLoaderListener(rootContext));

    }
	 /**
     * Factory method to create {@link AnnotationConfigWebApplicationContext} instances. 
     * @param annotatedClasses
     * @return
     */
    private AnnotationConfigWebApplicationContext createContext(final Class<?>... annotatedClasses) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(annotatedClasses);
        return context;
    }
    
    private void registerDispatcherServlet(ServletContext servletContext){
        AnnotationConfigWebApplicationContext dispatcherContext = createContext(WebMvcCtxConfig.class);

        DispatcherServlet dispatcherServlet=new DispatcherServlet(dispatcherContext);
        ServletRegistration.Dynamic dispatcher=servletContext.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
	}
}
